package com.lxd.milktea.controller;

import com.lxd.milktea.VO.ResultVO;
import com.lxd.milktea.constant.CookieConstant;
import com.lxd.milktea.constant.RedisConstant;
import com.lxd.milktea.dataobject.User;
import com.lxd.milktea.exception.SellException;
import com.lxd.milktea.service.UserService;
import com.lxd.milktea.util.CookieUtil;
import com.lxd.milktea.util.ResultVOUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 卖家用户
 * @Author Ha
 * @DATE 2019/6/5 20:47
 **/
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private final UserService userService;
    private final StringRedisTemplate stringRedisTemplate;

    public UserController(UserService userService, StringRedisTemplate stringRedisTemplate) {
        this.userService = userService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @PostMapping("/login")
    public ResultVO login(@RequestParam("username") String username, @RequestParam("password") String password,
                          Map<String,Object> maps, HttpServletResponse response){
            //用户名和密码去数据库匹配
        try{
            User user = userService.Login(username,password);
            //设置Token去Redis
            String token = UUID.randomUUID().toString();
            Integer expire = RedisConstant.EXPIRE;
            stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),username,expire, TimeUnit.SECONDS);
            //设置Token到cookie中
            CookieUtil.set(response, CookieConstant.TOKEN,token,CookieConstant.EXPIRE);
            return ResultVOUtil.success(user.getType());
        }catch (SellException e){
            return ResultVOUtil.fail(400,e.getMessage());
        }
    }

    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //清除Redis
            stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
            //清除cookie
            CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
        }
    }



    @PostMapping("/register")
    public ResultVO register(String username,String nickName,String userPassword,Integer type){
        User user = new User();
        user.setUserName(username);
        user.setNickName(nickName);
        user.setPassword(userPassword);
        user.setType(type.byteValue());
        userService.register(user);
        return ResultVOUtil.success();
    }

}
